var express = require('express');
var router = express.Router();

// 输出请求日志
router.use('*', function (req, res, next) {
    log4Req(req);
    next();
});

function log4Req(req) {
    var reqInfo = "request [ ip = %ip, url = %url ,body = %body]";
    reqInfo = reqInfo.replace('%ip', req.ip);
    reqInfo = reqInfo.replace('%url', req.url);
    reqInfo = reqInfo.replace('%body', req.body);
    console.log(reqInfo);
}


// 首页
router.get('/', function (req, res) {
    res.render('home', { title: '首页' });
});
router.get('/index', function (req, res) {
    res.render('home', { title: '首页' });
});

// 登录
router.get('/login', function (req, res) {
    res.render('login', { title: '登录' });
});

// 注册
router.get('/register', function (req, res) {
    res.render('register', { title: '注册' });
});
// 注册成功
router.post('/sign_up', function (req, res) {
    console.log('register');
    // 获取用户名和密码
    console.log(req.body);
    var userName = req.body.userName;
    var password = req.body.password;
    console.log('register:' + userName + " -- " + password);

    //
    var db = req.db;
    console.log('db ok');
    var collection = db.get('usercollection');
    console.log('usercollection ok');
    var toInsert = {
        'userName': userName,
        'password': password
    };
    collection.insert(toInsert, function (err, doc) {
        if (err) {
            console.log(err);
        } else {
            console.log('go index');
            // 回到首页
            res.location('/post')
            res.redirect('/post');
        }
    });
});

// 发表文章
router.get('/post', function (req, res) {
    res.render('post', { title: '发表文章' });
});

//*****************************************************//
// 测试 bootstrap 是否工作
router.get('/test/bootstrap', function (req, res) {
    res.render('test_bootstrap');
});

// 测试学习jade
router.get('/test/jade', function (req, res) {
    res.render('test_jade', {title: "test-jade", userlist: ['a', 'b']});
});

//// page not found
//router.get('*', function (req, res) {
//    res.render('error', { message: '~~找不到页面' });
//});

module.exports = router;
